package server2

import (
	"bufio"
	"fmt"
	"log"
	"net"
	"sync"
)

var mu sync.Mutex
var clients = make(map[net.Conn]string)

func main() {
	listener, err := net.Listen("tcp", ":8080")
	if err != nil {
		log.Println("启动失败:", err)
		return
	}
	defer listener.Close()
	log.Println("服务端启动成功")

	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Println("接受连接失败:", err)
			continue
		}
		log.Println("新客户端连接成功")

		mu.Lock()
		clients[conn] = conn.RemoteAddr().String()
		mu.Unlock()
		go handleConnection(conn)
	}
}

func handleConnection(conn net.Conn) {
	defer conn.Close()

	// 持续读取客户端消息
	scanner := bufio.NewScanner(conn)
	for scanner.Scan() {
		// 广播客户端发送的消息
		message := fmt.Sprintf("%s: %s\n", conn.RemoteAddr(), scanner.Text())
		broadcast(message)
	}
}

func broadcast(message string) {
	mu.Lock()
	defer mu.Unlock()
	for conn := range clients {
		_, err := conn.Write([]byte(message))
		if err != nil {
			log.Println("发送消息失败:", err)
		}
	}
}
